package com.linkq.ipinyin.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linkq.core.base.BaseService;
import com.linkq.ipinyin.common.utils.StringUtils;
import com.linkq.ipinyin.dao.ReplyDao;
import com.linkq.ipinyin.model.BcFile;
import com.linkq.ipinyin.model.Reply;
import com.linkq.ipinyin.utils.FileUtils;
import com.linkq.ipinyin.vo.ResultInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @FileName ReplyService
 * @Description
 * @Author wangpeng
 * @date 2025-03-01
 **/

@Service
public class ReplyService extends BaseService<ReplyDao, Reply> {
    @Autowired
    private FileService fileService;

    public ResultInfo submitRely(Reply reply, List<MultipartFile> files) {
        List<Reply> replyList = selectList(
                Wrappers.<Reply>lambdaQuery().eq(Reply::getFeedbackId, reply.getFeedbackId())
        );
        List<Integer> fileIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(files)) {
            for (MultipartFile file : files) {
                BcFile bcFile = FileUtils.upload(file);
                int fileId = fileService.insert(bcFile);
                fileIds.add(fileId);
            }
        }
        if (CollectionUtils.isNotEmpty(fileIds)) {
            reply.setFileIds(StringUtils.join(fileIds, ","));
        }
        reply.setReplyTime(new Date());
        Optional<Integer> maxOrder = replyList.stream().map(Reply::getSort).max(Integer::compareTo);
        if (maxOrder.isPresent()) {
            reply.setSort(maxOrder.get()+1);
        } else {
            reply.setSort(1);
        }
        if (insert(reply) > 0) {
            return ResultInfo.success(1, "答复成功");
        }
        return ResultInfo.error("答复失败", -1);
    }

    public ResultInfo getReplyByFeedbackId(Integer feedbackId) {
        List<Reply> replys = selectList(Wrappers.<Reply>lambdaQuery().eq(Reply::getFeedbackId, feedbackId));
        return ResultInfo.success(replys);
    }
}
